<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>promise红绿等</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      html,
      body {
        height: 100%;
      }
      #container {
        display: flex;
        height: 100%;
        justify-content: center;
        align-items: center;
      }
      #container div {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        background-color: rgba(176, 176, 176, 0.4);
        margin: 0 20px;
      }
      #container .green.active {
        background-color: green;
      }
      #container .yellow.active {
        background-color: yellow;
      }
      #container .red.active {
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div id="container">
      <div class="green active"></div>
      <div class="yellow"></div>
      <div class="red"></div>
    </div>
    <script>
      //需求分析
      //绿灯五秒黄灯
      //黄灯三秒红灯
      //红灯时6秒绿灯
      //Object.prototype.toString.call()

      //promise来处理交替效果
      //设置active类名让灯亮起来
      //获取元素
      let g = document.querySelector(".green");
      let y = document.querySelector(".yellow");
      let r = document.querySelector(".red");
      let divs = document.querySelectorAll("#container>div")
      //封装promis函数
      //传入延时的时间
      //灯亮的元素
      //调用dom排他思想
      function bright(timer, dom) {
        return new Promise((reslove, reject) => {
          setTimeout(() => {
            reslove(dom);
          }, timer);
        });
      }

      //开始让绿灯亮一次
      //善于用递归函数这是前端工程师必修课
      function recursion() {
        //直接调用成功的方法！！
        Promise.resolve()
          .then(() => {
            console.log("绿灯亮");
            css(g);
            return bright(1000, y);
          })
          .then((res) => {
            console.log(res);
             css(y);
            //成功变更才能执行
            return bright(1000, r);
          })
          .then((res) => {
            console.log(res);
            css(r);
            return bright(1000, g);
          })
          .then(() => {
            // console.log("亮绿");
            recursion();
          });
      }
      recursion();

      //处理dom样式的函数
      //
      function css(dom) {
         let bgc = dom.className;
        //  console.log([...divs]);
        [...divs].forEach((item)=>{
             let className = item.className;
             className = className.replace(/\sactive/,"");
            //  console.log(className);
             item.className = className;
        });
        dom.className = bgc+" active";
      }
    </script>
  </body>
</html>
